package cn.oi.klittle.era.widget.recycler;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewGroup;

import androidx.annotation.Nullable;

/**
 * 解决 RecyclerView嵌套RecyclerView滑动冲突的问题。这个亲测有效。
 * 这个直接作为嵌套RecyclerView使用，即：放在RecyclerView里面，外面放KRecyclerView或RecyclerView都可以。
 */
public class KRecyclerViewAtRecycleView extends KRecyclerView {

    private int startX, startY;

    public KRecyclerViewAtRecycleView(Context context) {
        super(context);
    }

    public KRecyclerViewAtRecycleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public KRecyclerViewAtRecycleView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }


    public KRecyclerViewAtRecycleView(ViewGroup viewGroup) {
        super(viewGroup.getContext());
        viewGroup.addView(this);//直接添加进去,省去addView(view)
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startX = (int) ev.getX();
                startY = (int) ev.getY();
                getParent().requestDisallowInterceptTouchEvent(true);
                break;
            case MotionEvent.ACTION_MOVE:
                int endX = (int) ev.getX();
                int endY = (int) ev.getY();
                int disX = Math.abs(endX - startX);
                int disY = Math.abs(endY - startY);
                if (disX > disY) {
                    getParent().requestDisallowInterceptTouchEvent(canScrollHorizontally(startX - endX));
                } else {
                    getParent().requestDisallowInterceptTouchEvent(canScrollVertically(startY - endY));
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                getParent().requestDisallowInterceptTouchEvent(false);
                break;
        }
        return super.dispatchTouchEvent(ev);
    }
}